package org.example;

import java.sql.*;
import java.text.MessageFormat;
import java.util.Scanner;

public class Demo1_DriverManager {
    public static void main(String[] args) {

        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;

        try {
            //1.加载数据库厂商提供的驱动包
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获得数据库连接
            connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/javatest?characterEncoding=utf8" +
                    "&allowPublicKeyRetrieval=true&useSSL=false", "root", "123456");
            //3.创建statement 对象
            statement = connection.createStatement();
            //4. 定义SQL
            System.out.println("请输入学生姓名：");
            Scanner in = new Scanner(System.in);
            //接收用户的输入
            String name = in.nextLine();
            String sql = "select student_id, sn, name, mail, class_id from student where name = '"+ name + "'";
            //5.执行 sql 语句
            resultSet = statement.executeQuery(sql);
            //6. 对结果集进行遍历，获取数据
            // 如果存在下一条记录，会返回true ,否则返回 false
            while(resultSet.next()) {
                //获得学生信息
                long stuId = resultSet.getLong(1);
                String stuSn = resultSet.getString(2);
                String stuNam = resultSet.getString(3);
                String stuMail = resultSet.getString(4);
                long claId = resultSet.getLong(5);
                //输出结果
                System.out.println(MessageFormat.format("学生编号={0}, 学号={1}, 姓名={2}, 邮箱={3}, 班级编号={4}",stuId,
                        stuSn,stuNam,stuMail,claId));
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            //资源关闭
            if(resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }

            if(statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }

            if(connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
